#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Author:liang futing
#@Time :2019/4/9 8:53
from django.shortcuts import render,redirect,reverse
from rbac.models import UserInfo,Role,Permission
from rbac.service.init_permission import init_permission

def login(request):
    if request.method=="GET":
        return render(request,'login.html')
    user=request.POST.get('user')
    pwd=request.POST.get('pwd')
    current_user=UserInfo.objects.filter(name=user,password=pwd).first()
    if not current_user:
        return render(request,'login.html',{'msg':'用户名或密码错误'})
    #根据用户信息存入用户权限
    #get user all permissions
    permissions_list1=current_user.roles.all().values_list("permissions__id","permissions__url").distinct()
    #有重复的问题

    # permissions_list2=Permission.objects.filter(role__in=current_user.roles.all()).values("url")
    # print(permissions_list1)
    init_permission(current_user,request)
    return redirect(reverse('web:customer_list'))

def logout(request):
    # 注销用户，等同于request.session.flush()
    # auth.logout(request)
    request.session.delete()
    request.session.flush()
    return redirect(reverse("web:login"))